import React, { useEffect, useState } from 'react';
import { ProForm, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { Card, message } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../../services/api';
import { User } from '../../types';

const UserForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [initialValues, setInitialValues] = useState<Partial<User>>();
  const isEdit = !!id;

  useEffect(() => {
    if (isEdit) {
      fetchUser();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const fetchUser = async () => {
    try {
      const response = await api.get(`/users/${id}`);
      setInitialValues(response.data);
    } catch (error: any) {
      message.error('Failed to fetch user details');
      navigate('/users');
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      if (isEdit) {
        await api.put(`/users/${id}`, values);
        message.success('User updated successfully');
      } else {
        await api.post('/users/', values);
        message.success('User created successfully');
      }
      navigate('/users');
    } catch (error: any) {
      message.error(error.response?.data?.detail || `Failed to ${isEdit ? 'update' : 'create'} user`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card title={isEdit ? 'Edit User' : 'Create User'}>
      <ProForm
        initialValues={initialValues}
        onFinish={handleSubmit}
        loading={loading}
        submitter={{
          searchConfig: {
            submitText: isEdit ? 'Update' : 'Create',
          },
          resetButtonProps: {
            onClick: () => navigate('/users'),
          },
        }}
      >
        <ProFormText
          name="username"
          label="Username"
          placeholder="Enter username"
          rules={[{ required: true, message: 'Please enter username' }]}
          disabled={isEdit}
        />

        <ProFormText
          name="email"
          label="Email"
          placeholder="Enter email"
          rules={[
            { required: true, message: 'Please enter email' },
            { type: 'email', message: 'Please enter a valid email' },
          ]}
        />

        {!isEdit && (
          <ProFormText.Password
            name="password"
            label="Password"
            placeholder="Enter password"
            rules={[
              { required: true, message: 'Please enter password' },
              { min: 6, message: 'Password must be at least 6 characters' },
            ]}
          />
        )}

        <ProFormSelect
          name="roles"
          label="Roles"
          mode="multiple"
          options={[
            { label: 'App User', value: 'AppUser' },
            { label: 'Platform User', value: 'PlatformUser' },
            { label: 'Administrator', value: 'Administrator' },
            { label: 'System Administrator', value: 'SystemAdministrator' },
          ]}
          rules={[{ required: true, message: 'Please select at least one role' }]}
          placeholder="Select roles"
        />

        <ProFormText
          name="tenantId"
          label="Tenant ID"
          placeholder="Enter tenant ID"
          rules={[{ required: true, message: 'Please enter tenant ID' }]}
          fieldProps={{ type: 'number' }}
        />
      </ProForm>
    </Card>
  );
};

export default UserForm;
